﻿using MediatR;
using SystemWFH.API.Application.Command.EquipmentCommand;
using SystemWFH.API.DTO;
using SystemWFH.Domain;
using SystemWFH.Infrstructer.Impl;
using SystemWFH.Infrstructer.Interface;

namespace SystemWFH.API.Application.CommandHandlers.EquipmentCommandHandler
{
    public class EquipmentGetAllCommandHandler : IRequestHandler<EquipmentGetAllCommand, PageDTO<Equipment>>
    {
        /// <summary>
        /// 服务
        /// </summary>
        private readonly IEquipmentRepository equipmentRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="equipmentRepository">服务</param>
        public EquipmentGetAllCommandHandler(IEquipmentRepository equipmentRepository)
        {
            this.equipmentRepository = equipmentRepository;
        }
        public async Task<PageDTO<Equipment>> Handle(EquipmentGetAllCommand request, CancellationToken cancellationToken)
        {
            PageDTO<Equipment> page = new PageDTO<Equipment>();
            var list = await equipmentRepository.GetAllAsync();
            list = list.Where(x => x.IsDelete == false).ToList();
            if (!string.IsNullOrEmpty(request.equipmentName))
            {
                list = list.Where(x => x.equipmentName.Contains(request.equipmentName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.equipmentNumbering))
            {
                list = list.Where(x => x.equipmentNumbering.Contains(request.equipmentNumbering)).ToList();
            }
            if (request.equipmentState > 0)
            {
                list = list.Where(x => x.equipmentState == request.equipmentState).ToList();
            }
            //if (!string.IsNullOrEmpty(request.invoiceDate))
            //{
            //    list = list.Where(x => x.invoiceDate == DateTime.Parse(request.invoiceDate)).ToList();
            //}
            page.listCount = list.Count;
            page.pageCount = (int)Math.Ceiling(page.listCount * 1.0 / request.pageSize);
            page.pageList = list.OrderByDescending(x => x.equipmentId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return page;
        }
    }
}
